package com.java.simple.study.juc.p2;

import com.java.simple.study.tool.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.LockSupport;

/**
 * @author zhoujunlin
 * @date 2022年04月05日 15:46
 * @desc
 */
@Slf4j(topic = "c.TestInterrupt")
public class TestInterrupt {

    public static void main(String[] args) throws InterruptedException {
//        test1();
//        test2();
//        test3();
        test4();
    }


    private static void test1() {
        Thread t1 = new Thread(() -> {
            Sleeper.sleep(5);
        }, "t1");
        t1.start();

        // 主线程停一秒后打断t1
        Sleeper.sleep(1);
        t1.interrupt();
        // sleep被打断后抛出异常会清除打断标记  false
        log.debug("打断状态：{}", t1.isInterrupted());
    }

    private static void test2() {
        Thread t2 = new Thread(() -> {
            while (true) {
                Thread thread = Thread.currentThread();
                boolean interrupted = thread.isInterrupted();
                if (interrupted) {
                    log.debug("打断状态：{}", interrupted);
                    break;
                }
            }
        }, "t2");
        t2.start();

        // 主线程停一秒后打断t2
        Sleeper.sleep(1);
        // 正在运行的线程 被打断不会抛出异常 打断标记不会清除
        t2.interrupt();
    }

    private static void test3() {
        Thread t3 = new Thread(() -> {
            log.debug("park.....");
            LockSupport.park();
            log.debug("unpark...");
            log.debug("打断状态：{}", Thread.currentThread().isInterrupted());
            // 无效代码 park方法不生效了 当前线程已经是被打断状态
            LockSupport.park();
            log.debug("还会运行");
        }, "t3");
        t3.start();

        // 主线程停一秒后打断t3
        Sleeper.sleep(1);
        // WAITING
        log.debug("t3线程状态：{}", t3.getState());
        // park线程不会清除打断标记
        t3.interrupt();
    }

    private static void test4() throws InterruptedException {
        Thread t4 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                log.debug("park...");
                LockSupport.park();
                // 由于不会清除打断标记  后面循环依旧执行
                log.debug("打断状态：{}", Thread.currentThread().isInterrupted());
                // 由于此方法会清除打断标记 所以第二次循环会park住 一直等待
                //log.debug("打断状态：{}", Thread.interrupted());
            }
        }, "t4");
        t4.start();

        // 主线程停一秒后打断t4
        Sleeper.sleep(1);
        // park线程不会清除打断标记
        t4.interrupt();
    }

}
